package test.single_task;

import beautiful.butterfly.distributed_task_processing_engine.api.SingleTaskDataItemCollectorAndExecuterAndExecuter;
import beautiful.butterfly.distributed_task_processing_engine.task_manage.task_data_items_processor.task_data_item_data_manager.TaskItemStringAndParameterString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 单个任务处理实现
 */
public class DBDemoSingleTask implements SingleTaskDataItemCollectorAndExecuterAndExecuter<Long>
{

    private static transient Logger log = LoggerFactory.getLogger(DBDemoSingleTask.class);

    protected DataSource dataSource;


    public Comparator<Long> getComparator()
    {
        return new Comparator<Long>()
        {
            public int compare(Long o1, Long o2)
            {
                return o1.compareTo(o2);
            }

            public boolean equals(Object obj)
            {
                return this == obj;
            }
        };
    }

    @Override
    public List<Long> getTaskDataItemList(String taskParameter, int fetchTaskDataItemNum, int taskItemNum, List<TaskItemStringAndParameterString> taskItemStringAndParameterStringList) throws Exception
    {
        List<Long> result = new ArrayList<Long>();
        if (taskItemStringAndParameterStringList.size() == 0)
        {
            return result;
        }

        StringBuffer condition = new StringBuffer();
        for (int i = 0; i < taskItemStringAndParameterStringList.size(); i++)
        {
            if (i > 0)
            {
                condition.append(",");
            }
            condition.append(taskItemStringAndParameterStringList.get(i).getTaskItemString());
        }

        Connection connection = null;
        try
        {
            connection = dataSource.getConnection();

            String sql = null;
            sql = "select ID from SCHEDULE_TEST where  mod(id," + taskItemNum + ") in ("
                    + condition.toString() + ") and sts ='N' LIMIT "
                    + fetchTaskDataItemNum;
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next())
            {
                result.add(resultSet.getLong("ID"));
            }
            resultSet.close();
            preparedStatement.close();
            return result;
        } finally
        {
            if (connection != null)
                connection.close();
        }
    }

    @Override
    public boolean dealWith(Long id) throws Exception
    {
        Connection connection = null;

        try
        {
            connection = dataSource.getConnection();
            String sql = "update SCHEDULE_TEST SET STS ='Y' ,DEAL_COUNT = DEAL_COUNT + 1 WHERE ID = ? and STS ='N' ";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setLong(1, id);
            preparedStatement.executeUpdate();
            preparedStatement.close();
            connection.commit();
            log.debug("处理任务：" + id + " 成功！");
            return true;
        } catch (Exception e)
        {
            log.error("执行任务：" + id + "失败：" + e.getMessage(), e);
            if (connection != null)
            {
                connection.rollback();
            }
            return false;
        } finally
        {
            if (connection != null)
            {
                connection.close();
            }
        }
    }

    public DataSource getDataSource()
    {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource)
    {
        this.dataSource = dataSource;
    }


}